package com.sdwl.brcl.dao.datasource;

import com.alibaba.fastjson.JSON;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;


@Configuration
@MapperScan(basePackages = "com.sdwl.brcl.dao.mapper", sqlSessionFactoryRef = "chainSqlSessionFactory")
public class ChainDBDataSource {

	@Autowired
	private ChainDBConfig chainDBConfig;

	@Primary
	@Bean(name = "chainDataSource")
	public DataSource dataSource() {
		HikariDataSource dataSource = new HikariDataSource();
		dataSource.setJdbcUrl(chainDBConfig.getUrl());
		dataSource.setUsername(chainDBConfig.getUsername());
		dataSource.setPassword(chainDBConfig.getPassword());
		dataSource.setMinimumIdle(chainDBConfig.getMinimumIdle());
		dataSource.setIdleTimeout(chainDBConfig.getIdleTimeout());
		dataSource.setMaximumPoolSize(chainDBConfig.getMaximumPoolSize());
		dataSource.setAutoCommit(chainDBConfig.getAutoCommit());
		dataSource.setPoolName(chainDBConfig.getPoolName());
		dataSource.setMaxLifetime(chainDBConfig.getMaxLifetime());
		dataSource.setConnectionTimeout(chainDBConfig.getConnectionTimeout());
		dataSource.setConnectionTestQuery(chainDBConfig.getConnectionTestQuery());
		dataSource.setDriverClassName(chainDBConfig.getDriverClassName());
		return dataSource;
	}

	@Primary
	@Bean(name = "chainSqlSessionFactory")
	public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("chainDataSource") DataSource datasource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(datasource);
		//mybatis扫描xml所在位置
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
		return bean.getObject();
	}


	@Primary
	@Bean(name = "chainTransactionManager")
	public DataSourceTransactionManager transactionManager() throws SQLException {
		return new DataSourceTransactionManager(dataSource());
	}



}
